import React, { useEffect, useState } from 'react'
import styles from './index.module.less'
import { IMenuItem } from '@/types/menu'
import { useLocation, useNavigate, useRouteLoaderData } from 'react-router-dom'
import TagItem, { ITagItem } from './components/TagItem'
import { IAuthLoader } from '@/router/AuthLoader'

const TagsView: React.FC = () => {
  const [tagsviewList, setTagsViewList] = useState<ITagItem[]>([])
  const { menuList } = useRouteLoaderData('root') as IAuthLoader
  const { pathname } = useLocation()
  const navigate = useNavigate()
  useEffect(() => {
    addTagsView(pathname)
  }, [pathname])

  const searchRoute = (tree: IMenuItem[], pathName: string): any => {
    if (!tree || !pathName) return
    for (const item of tree) {
      if (item.path === pathName) return item
      if (item.children && item.children.length) {
        const searchRes = searchRoute(item.children, pathName)
        if (searchRes) return searchRes
      }
    }
    return ''
  }

  const addTagsView = (pathname: string) => {
    // 已存在return
    if (tagsviewList.map(item => item.path).includes(pathname)) return
    const result = searchRoute(menuList, pathname)
    setTagsViewList([...tagsviewList, result])
  }

  const handleClose = (item: ITagItem) => {
    const filterList = tagsviewList.filter(tagsview => tagsview.path !== item.path)
    console.log('handleClose:', filterList)
    setTagsViewList([...filterList])
    // 如果删除的是当前路由，跳转到最后一个
    const lastTag = filterList.slice(-1)[0]
    if (lastTag) {
      navigate(lastTag.path || '/')
    } else {
      navigate('/')
    }
  }

  return (
    <div className={styles.tagsview}>
      {tagsviewList.length > 0 &&
        tagsviewList.map((tagsview, index) => (
          <TagItem {...tagsview} onClose={handleClose} index={index} key={index} />
        ))}
    </div>
  )
}

export default TagsView
